<?php
namespace app\controllers;

use Yii;
use app\components\BaseController;
use app\components\Api;
use app\components\Loyalty;
use app\components\Log;
use app\models\Tenant;
use yii\web\ServerErrorHttpException;

class CampaignController extends BaseController
{
	public $enableCsrfValidation = false;
	
	/**
	 * JSelect Artistic Campaign
	 * 8.6 - 8.15
	 */
	public function actionArtistic()
	{
		$oauth = Yii::$app->request->get('oauth');
		
		// wechat 
		if ($oauth === 'Y') {
			$userInfo = $this->getUserInfo();
			$openid = $this->getOpenid();
			$appid = $this->getAppid();
			if ($userInfo['status'] == 'success') {
				$webform_url = '';
				$couponStatus = 'y';
				$jumpStatus = 'y';
			} else {
				$webform_url = Tenant::find()->select('webform_url')->where(['appid' => $this->appid])->scalar();
				$webform_url = $webform_url . '&openid=' . $openid . '&appid=' . $appid;
				Log::debug('webform_url', $webform_url);
				$couponStatus = 'n';
				$jumpStatus = 'n';
			}
			
			$source = 'wechat';
		// sms
		} else {
			$appid = 'wxeca2e361be1de14c';
			$this->bootstrap($appid);
			
			$mobile = Yii::$app->request->get('mobile');
			if (empty($mobile)) {
				throw new ServerErrorHttpException('mobile not found.');
			}
			if (substr($mobile, 0, 2) != '86') {
				$mobile = '86' . $mobile;
			}
			
			$userInfo = Loyalty::customer_get(['mobile' => $mobile]);
			if ($userInfo['status'] == 'success') {
				$userInfo['card_number'] = $userInfo['membership']['card_number'];
				$userInfo['code'] = $userInfo['membership']['code'];
				$this->setUserInfo($userInfo); // 重要方法！把该用户的微信信息和Loyalty信息存到session中
				$webform_url = '';
				$couponStatus = 'y';
				$jumpStatus = 'y';
			} else {
				$webform_url = Tenant::find()->select('webform_url')->where(['appid' => $this->appid])->scalar();
				$couponStatus = 'n';
				$jumpStatus = 'n';
			}
			
			$source = 'sms';
		}
		
		return $this->renderPartial('jselect/artistic', [
				'source' => $source,
				'userInfo' => json_encode($userInfo),
				'webform_url' => $webform_url,
				'couponStatus' => $couponStatus,
				'jumpStatus' => $jumpStatus,
		]);
	}
	
	public function actionAjaxSendArtisticCoupon()
	{
		$userInfo = $this->getUserInfo();
		if (empty($userInfo)) {
			return json_encode(['status' => 'error', 'message' => 'userInfo is empty.']);
		}
		
		$re = Loyalty::trigger_earnrule(['code' => $userInfo['code'], 'event' => 'Jselect sen Coupon']);

		if ($re['status'] == 'success') {
			$r = current($re['triggered_events']);
			$r = current($r['rewards'][$r['event_id']]);
			if ($r['status'] == 'failed') {
				return json_encode(['status' => 'error', 'message' => 'Coupon have already sent.']);
			} else {
				return json_encode(['status' => 'success', 'message' => 'Send Coupon Success.']);
			}
		} else {
			return json_encode(['status' => 'error', 'message' => 'Send Coupon Failed.']);
		}
	}
	
	/**
	 * bootstrap function for basic appid, userinfo
	 * @param string $appid
	 * @param array $userInfo
	 * @throws ServerErrorHttpException
	 */
	protected function bootstrap($appid)
	{
		Log::debug('Campaign bootstrap GET FIELDS', $_GET);
				
		if (empty($appid)) {
			throw new ServerErrorHttpException('appid not found');
		}
		// 重要！获取appid，作为全局支持
		$this->setAppid($appid);
		
		// 设置identifier
		$tenant = Tenant::find()->where(['appid' => $appid])->one();
		
		if (empty($tenant->identifier)) {
			throw new ServerErrorHttpException('identifier not found');
		}
		$this->setIdentifier($tenant->identifier);
		
		// 设置loyalty config
		if (empty($tenant->tenant_id) || empty($tenant->loyalty_accountid) || empty($tenant->loyalty_username) || empty($tenant->loyalty_password)) {
			throw new ServerErrorHttpException('loyalty config not found');
		} else {
			$session = Yii::$app->session;
			$loyaltyConfig = [
				'tenant_id' => $tenant->tenant_id,
				'app_id' => $tenant->appid,
				'loyalty_accountid' => $tenant->loyalty_accountid,
				'loyalty_username' => $tenant->loyalty_username,
				'loyalty_password' => $tenant->loyalty_password,
				'loyalty_url' => $tenant->loyalty_url,
			];
			$session->set('loyaltyConfig', $loyaltyConfig);
		}
	}
}